#!/bin/bash

# Tiny QA - 稳定Docker构建脚本
# 包含网络重试和错误处理机制

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 配置
IMAGE_NAME="tiny-qa"
TAG="latest"
BUILD_CONTEXT="."

echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE}Tiny QA - 稳定Docker构建${NC}"
echo -e "${BLUE}========================================${NC}"
echo -e "${YELLOW}🔧 构建参数:${NC}"
echo -e "  镜像名称: ${IMAGE_NAME}:${TAG}"
echo -e "  构建上下文: ${BUILD_CONTEXT}"
echo ""

# 检查Docker是否运行
if ! docker info > /dev/null 2>&1; then
    echo -e "${RED}❌ Docker未运行，请先启动Docker Desktop${NC}"
    exit 1
fi

# 清理旧镜像（可选）
read -p "是否清理旧的构建缓存？(y/N): " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
    echo -e "${YELLOW}🧹 清理构建缓存...${NC}"
    docker builder prune -f
    echo -e "${GREEN}✅ 缓存清理完成${NC}"
fi

echo -e "${YELLOW}🚀 开始构建镜像...${NC}"
echo -e "${YELLOW}⏱️  预计时间: 3-8分钟${NC}"
echo ""

# 构建函数，包含重试机制
build_with_retry() {
    local max_attempts=3
    local attempt=1
    
    while [ $attempt -le $max_attempts ]; do
        echo -e "${BLUE}📦 构建尝试 ${attempt}/${max_attempts}${NC}"
        
        if docker build \
            --tag "${IMAGE_NAME}:${TAG}" \
            --file Dockerfile \
            --progress=plain \
            --no-cache \
            "${BUILD_CONTEXT}"; then
            echo -e "${GREEN}✅ 构建成功！${NC}"
            return 0
        else
            echo -e "${RED}❌ 构建失败 (尝试 ${attempt}/${max_attempts})${NC}"
            
            if [ $attempt -lt $max_attempts ]; then
                echo -e "${YELLOW}🔄 等待 10 秒后重试...${NC}"
                sleep 10
            fi
        fi
        
        attempt=$((attempt + 1))
    done
    
    echo -e "${RED}❌ 所有构建尝试都失败了${NC}"
    return 1
}

# 执行构建
if build_with_retry; then
    echo ""
    echo -e "${GREEN}🎉 镜像构建完成！${NC}"
    echo -e "${BLUE}📋 镜像信息:${NC}"
    docker images "${IMAGE_NAME}:${TAG}"
    
    echo ""
    echo -e "${BLUE}🚀 运行命令:${NC}"
    echo -e "  docker run -d -p 5002:5002 --name tiny-qa ${IMAGE_NAME}:${TAG}"
    echo ""
    echo -e "${BLUE}🔍 查看日志:${NC}"
    echo -e "  docker logs -f tiny-qa"
    echo ""
    echo -e "${BLUE}🌐 访问地址:${NC}"
    echo -e "  http://localhost:5002"
else
    echo -e "${RED}❌ 构建失败！${NC}"
    echo -e "${YELLOW}💡 建议:${NC}"
    echo -e "  1. 检查网络连接"
    echo -e "  2. 确保Docker Desktop正在运行"
    echo -e "  3. 尝试使用开发环境构建: ./scripts/docker-build-dev.sh"
    exit 1
fi 